<?php 

namespace app\common\shop;

use think\Db;
use think\Model;
use think\model\concern\SoftDelete;


class SpecModel extends model {
//    use SoftDelete;//开启了软删除
//    protected  $deleteTime= 'del_time';
    // 完整数据表名
    protected $table = 'shop_spec';


    /**
     * [建表]
     * @return
     */
    public static function createTable(){
        return Db::query("CREATE TABLE If Not Exists `shop_spec` (
             `id` int(11) NOT NULL AUTO_INCREMENT,
             `goodsid` int(11) NOT NULL DEFAULT '0' COMMENT '商品id',
             `title` varchar(255) NOT NULL COMMENT '标题',
             `pid` int(11) NOT NULL DEFAULT '0' COMMENT '上级id',
             `createtime` int(10) unsigned NOT NULL DEFAULT '0' COMMENT '创建时间',
             PRIMARY KEY (`id`)
            ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COMMENT='规格表'");
    }
 	/**
     * [添加]
     * @return
    */
    public static function add($data){
    	$data['createtime'] = time();
    	return self::insertGetId($data);
    }

    /**
     * [单条数据]
     * @return
    */
    public static function getInfo($id){
        return self::where('id',$id)->find();
    }

    /**
     * [获取相应数据]
     * @return
    */
    public static function getList($goodsid=0){
        return self::where('goodsid',$goodsid)->where('pid',0)->order('id desc')->select();
    }

    /**
     * [获取下级的数据]
     * @return
    */
    public static function getPidSpec($pid=0,$field='*',$goodsid=0){
        return self::where('goodsid',$goodsid)->field($field)->where('pid',$pid)->select();
    }

    /**
     * [获取下级的数据]
     * @return
    */
    public static function getIdSpec($id=0,$field='*',$goodsid=0){ 
        return self::where('goodsid',$goodsid)->field($field)->where('id',$id)->select();
    }

    /**
     * [规格名称]
     * @param
     * @return
     */
    public static function getSpecTitle($key,$goodsid){
        $id = str_replace('_',',',$key);
        $title = self::where('id','in',$id)
            ->where('goodsid',$goodsid)
            ->orderRaw('field(`id`,'.$id.')')
            ->column('title');
        return implode(';',$title);
    }

    /**
     * [商品规格]
     * @param
     * @return
     */
    public static function getGoodsSpec( $specList ){

        // 规格列表
        $spec_title = '';
        $allkey = [];
        foreach ($specList as $key => &$value) {
            $key = explode('_',$value['key']);

            $imkey = implode(',',$key);
            if(empty($pid)){
                // 按照相应id排序
                $pid = SpecModel::where('id','in',$imkey)->orderRaw('field(`id`,'.$imkey.')')->column('pid');
                $ppid = implode(',',$pid);
                // 按照相应id排序
                $spec_title = self::where('id','in',$ppid)->orderRaw('field(`id`,'.$ppid.')')->field('id,title')->select()->toArray();

            }

            $allkey = array_unique (array_merge($allkey,$key));
            $title = SpecModel::where('id','in',$imkey)->orderRaw('field(`id`,'.$imkey.')')->column('title');
            $stitle = implode('|_|',$title);

            $value['title'] = $stitle;
            $goodsid = $value['goodsid'];
        }
        unset($value);
        // 规格下级的所有数据
        foreach ($spec_title as $key => $value) {
            $spec_title[$key]['pid_spec'] = SpecModel::getPidSpec($value['id'],'id,pid,title',$goodsid)->toArray();
        }

        $spec_info_list = SpecModel::where('id','in',implode(',',$allkey ))->field('id,pid,title')->select()->toArray();
        $have_id = [];
        // 计算哪个规格已经选择
        foreach ($spec_title as $k => $v) {
            foreach ($spec_info_list as $key => $value) {
                if($value['pid'] == $v['id'] && !in_array($value['id'],$have_id)){

                    $have_id[] = $value['id'];// 已经有计算过的，不重复计算
                    foreach ($v['pid_spec'] as $ke => $val) {

                        if($value['id'] == $val['id']){
                            $spec_title[$k]['pid_spec'][$ke]['isset'] =1;
                            continue;
                        }
                    }
                }
            }
        }

        foreach ($spec_title as $key => $value) {
            foreach ($value['pid_spec'] as $ke => $val) {
                if(!isset($val['isset'])){
                    $spec_title[$key]['pid_spec'][$ke]['isset'] =0;
                }
            }
        }

        $list = [
            'spec'=>$specList,
            'spec_title'=>$spec_title,
        ];
        return $list;
    }

    /**
     * [前端商品规格]
     * @param
     * @return
     */
    public static function indexGoodsSpec( $speclist ){
        $allkey = [];
        foreach ($speclist as $key => $value) {
            $key = explode('_',$value['key']);

            $imkey = implode(',',$key);
            if(empty($pid)){
                $pid = SpecModel::where('id','in',$imkey)->orderRaw('field(`id`,'.$imkey.')')->column('pid');
                $ppid = implode(',',$pid);
                $spec_title = (SpecModel::where('id','in',$ppid)->orderRaw('field(`id`,'.$ppid.')')->field('id,title')->select())->toArray();
            }
            $allkey = array_unique(array_merge($allkey,$key));
        }

        foreach ($allkey as $key => $value) {
            $info = SpecModel::getInfo($value);
            foreach ($spec_title as $k => $v) {

                if($v['id'] == $info['pid']){

                    $all[$v['id']][] = [
                        'id'=>$info['id'],
                        'title'=>$info['title'],
                    ];
                    $spec_title[$k]['pid_spec'] = $all[$v['id']];
                }
            }
        }
//        $goods['spec_title'] = $spec_title;
        return $spec_title;
    }
}